package com.ruoyi.system.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.config.AliPayController;
import com.ruoyi.system.service.IDsStoragemanagementService;
import com.ruoyi.system.util.AmountCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.ruoyi.system.domain.DsStoragemanagement;

@RestController
@RequestMapping("/VehicleInfo")
public class SxTController extends BaseController {
    @Autowired
    private IDsStoragemanagementService dsStoragemanagementService;
    @Autowired
    AliPayController aliPayController;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @RequestMapping("/getCarNo")
    public AjaxResult getCarNo(HttpServletRequest request) {
        StringBuffer jb = new StringBuffer();
        char[] lineChars = new char[1024 * 1024];
        char[] totalChars = new char[1024 * 1024];
        int readLen = 0;
        int totalLen = 0;
        try {
            BufferedReader reader = request.getReader();
            while ((readLen = reader.read(lineChars)) > 0) {
                for (int i = 0; i < readLen; i++) {
                    totalChars[totalLen + i] = lineChars[i];
                }
                totalLen += readLen;
            }
        } catch (Exception e) {
            e.printStackTrace(); /*report an error*/
            return AjaxResult.error("获取车牌号时出错");
        }

        String lineStr = new String(totalChars);
        try {
            JSONObject jsonObject = JSON.parseObject(lineStr);
            if (jsonObject == null) {
                return AjaxResult.error("无法解析JSON数据");
            }

            // 解析JSON数据,获取车牌号
            String license = jsonObject
                    .getJSONObject("AlarmInfoPlate")
                    .getJSONObject("result")
                    .getJSONObject("PlateResult")
                    .getString("license");
            if (license == null || license.isEmpty()) {
                return AjaxResult.error("无法获取车牌号");
            }
            // 将车牌号打印出来
            System.out.println("车牌号: " + license);

            // 查询车辆是否已入库
            long pduanid = dsStoragemanagementService.getselectIDSoto(license);
            if (pduanid == 0) {
                long vehicleId;
                int mation = getVehicleinformation(license); // 查看是否为会员用户
                int erinfo = getVehicleownerinfo(license); // 查看是否为固定业主
                if (mation != 0) {
                    vehicleId = getCharacters(mation, 1);
                } else if (erinfo != 0) {
                    vehicleId = getCharacters(erinfo, 2);
                } else {
                    vehicleId = getLingShi(0, 0); // 添加为临时用户
                }
                DsStoragemanagement ds = new DsStoragemanagement();
                ds.setVehicleId(vehicleId); // 角色id
                ds.setLicenseplate(license); // 车牌号
                int result = dsStoragemanagementService.insertDsStoragemanagement(ds);

                // 将车牌号、出库时间和金额存入Redis
                LocalDateTime now = LocalDateTime.now();
                ZoneId zoneId = ZoneId.systemDefault();
                ZonedDateTime zdt = now.atZone(zoneId);
                Date deliveryDateTime = Date.from(zdt.toInstant());
                long jiner = AmountCalculation.jiner(ds.getStorageDateTime(), deliveryDateTime); // 计算金额

                if (redisTemplate!=null){
                    // 将车牌号、出库时间和金额存入Redis
                    redisTemplate.opsForHash().put("vehicle_info", "license_plate", license);
                    redisTemplate.opsForHash().put("vehicle_info", "delivery_date_time", deliveryDateTime.toString());
                    redisTemplate.opsForHash().put("vehicle_info", "amount", String.valueOf(jiner));
                    redisTemplate.expire("vehicle_info", 7, TimeUnit.DAYS); // 设置7天过期
                }



                return toAjax(result);
            } else {
                DsStoragemanagement dsime = new DsStoragemanagement();
                dsime.setStorageId(pduanid);
                dsime = dsStoragemanagementService.selectDsStoragemanagementByStorageId(dsime);
                LocalDateTime now = LocalDateTime.now();
                ZoneId zoneId = ZoneId.systemDefault();
                ZonedDateTime zdt = now.atZone(zoneId);
                Date deliveryDateTime = Date.from(zdt.toInstant());
                dsime.setDeliveryDateTime(deliveryDateTime); // 出库时间
                long jiner = AmountCalculation.jiner(dsime.getStorageDateTime(), deliveryDateTime); // 计算金额
                String randomString = generateRandomString(21);
                dsime.setOrdernumber(randomString); // 订单号
                dsime.setAmount(jiner);
                long i = 1;
                dsime.setOperationType(i);
                int ida = dsStoragemanagementService.updateDsStoragemanagement(dsime);

                if (redisTemplate!=null){
                    // 将车牌号、出库时间和金额存入Redis
                    redisTemplate.opsForHash().put("vehicle_info", "license_plate", license);
                    redisTemplate.opsForHash().put("vehicle_info", "delivery_date_time", deliveryDateTime.toString());
                    redisTemplate.opsForHash().put("vehicle_info", "amount", String.valueOf(jiner));
                    redisTemplate.expire("vehicle_info", 7, TimeUnit.DAYS); // 设置7天过期
                }


                return toAjax(ida);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("处理车牌号时出错");
        }
    }
    public int getVehicleinformation(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleinformation(vehicleInfo);
    }

    public int getVehicleownerinfo(String vehicleInfo) {
        return dsStoragemanagementService.getVehicleownerinfo(vehicleInfo);
    }

    public int getCharacters(int id, int mid) {
        return dsStoragemanagementService.getCharacters(id, mid);
    }

    public int getLingShi(int id, int biao) {
        return dsStoragemanagementService.getLingShi(id, biao);
    }

    public static String generateRandomString(int length) {
        String charPool = "0123456789";
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charPool.length());
            sb.append(charPool.charAt(index));
        }
        return sb.toString();
    }

    //            WriteTxt("d:\\plate_num.txt", license);
    //把json字符串以txt文件的形式保存
    protected void WriteTxt(String path, String txt) {
        try {
            FileWriter f = new FileWriter(path);
            BufferedWriter bw = new BufferedWriter(f);
            bw.write(txt);
            bw.close();
        } catch (Exception e) {
        }
    }



}


